<?php
class Pageley_Mapper_ManyToManyMap extends Pageley_Util_ArrayMap {
    private $references;
    private $relationType;
    private $referencingEntity;
    private $referencingPropertyName;
    private $referencedPropertyName;
    
    public function __construct($entries, $relationType, $referencedPropertyName, $referencingEntity) {
        parent::__construct($entries);
        $this->relationType = $relationType;
        $this->referencingEntity = $referencingEntity;
        $this->referencingPropertyName = Pageley_Util_String::uncapitalize($referencingEntity->getType()->getName());
        $this->referencedPropertyName = $referencedPropertyName;
    }
    
    public function add($value) {
        $entry = $this->relationType->newInstance();
        $entry->set($this->referencedPropertyName, $value);
        $entry->set($this->referencingPropertyName, $this->referencingEntity);
        parent::add($entry);
    }
    
    public function removeValue($value) {
        $key = null;
        foreach($this->toArray() as $k => $entry) {
            if($value == $entry) {
                $key = $k;
                break;
            }
        }
        parent::remove($key);
    }
    
    public function containsValue($value) {
        $result = false;
        foreach($this->toArray() as $key => $entry) {
            if($value == $entry) {
                $result = true;
                break;
            }
        }
        return $result;
    }
    
    public function get($key) {
        $entry = parent::get($key);
        return $this->getReference($entry);
    }
    
    public function getIterator() {
        $references = new Pageley_Util_ArrayMap();
        foreach($this->toArray() as $key => $entry) {
            $references->put($key, $this->getReference($entry));
        }
        return new ArrayIterator($references->toArray());
    }
    
    private function getReference($entry) {
        $result = null;
        if($entry !== null) {
            $result = $entry->get($this->referencedPropertyName);
        }
        return $result;
    }
}